#!/python/env/python3.5/bin/python
# coding:utf-8
import itchat
import time, os, json, re, random
import requests

TBID_DIR_PATH = '/tmp/tbid'
IMG_SAVE_PATH = '/tmp'
random.seed()

def getChatrooms(imgPath, slogan):
    chatroom = itchat.search_chatrooms('一带一路天猫福利35群')
    for room in chatroom:
        itchat.send("@img@%s" % imgPath, room['UserName'])
        time.sleep(random.randint(1,5))
        itchat.send(slogan, room['UserName'])
        time.sleep(random.randint(10,60))

def getPubImg(tbid):
    url = 'http://api.zaizaihui.cn/tool/goods/ext/img2/' + tbid
    r = requests.get(url, stream=True)
    if r.status_code == 200:
        open(IMG_SAVE_PATH + '/' + tbid + '.jpeg', 'wb').write(r.content)
        return IMG_SAVE_PATH + '/' + tbid + '.jpeg'
    return ''

def getMemuu():
    url = 'http://www.memuu.com/api/v2/miaosha?search=&page=1&count=20&cid=0&from=mobileWeb&c_num=0&hidehb=0&token=null&appid=null';
    r = requests.get(url, stream=True)
    if r.status_code == 200:
        data = r.json()
        sendNum = 10
        sendTbid = ''
        for goods in data['goods']:
            sendTbid = sendTbid + goods['tbid'] + ' '
            sendNum = sendNum - 1
            if sendNum == 0:
                break

        #如果获取的记录和上次发送的记录一样,就不发送了
        try:
            f = open('/tmp/sendlog', 'w+')
            log = f.read()
            if log == sendTbid:
                return
            for goods in data['goods']:
                tbid = goods['tbid']
                slogan = goods['slogan']
                if tbid in log:
                    continue
                else:
                    imgPath = getPubImg(tbid)
                    if(imgPath == ''):
                        continue
                    getChatrooms(imgPath, slogan)
            f.write(sendTbid)
        finally:
            f.close()

itchat.auto_login(True)

while True:
    getMemuu()
    time.sleep(random.randint(400,700))

itchat.run()
